package dk.ucn.testalarmen;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Page2 extends Activity {

	private static final String TAG = "RejseAlarmen";

	ArrayList<Trip> tripList;
	ArrayList<Leg> legs;

	String originName = null;
	String originX = null;
	String originY = null;
	String originId = null;
	String originType = null;

	String destName = null;
	String destX = null;
	String destY = null;
	String destId = null;
	String destType = null;

	String date = null;
	String time = null;

	String useBus = null;
	String useTrain = null;
	String useMetro = null;

	Button buttonFirstTrip;
	Button buttonSecondTrip;
	Button buttonThirdTrip;
	Button button_earlier_trips;
	Button button_later_trips;


	TextView tvDate;
	private String baseUrl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_page2);
		Log.d(TAG, "Page2 onCreate called");

		// Show the Up button in the action bar.
		setupActionBar();
		tripList = new ArrayList<Trip>();
		legs = new ArrayList<Leg>();
		baseUrl = (String) getText(R.string.baseUrl);

		buttonFirstTrip = (Button) findViewById(R.id.button_first_trip);
		buttonSecondTrip = (Button) findViewById(R.id.button_second_trip);
		buttonThirdTrip = (Button) findViewById(R.id.button_third_trip);
		button_earlier_trips = (Button) findViewById(R.id.button_earlier_trips);
		button_later_trips = (Button) findViewById(R.id.button_later_trips);
		tvDate = (TextView) findViewById(R.id.tv_date);

		savedInstanceState = getIntent().getExtras();
		final String myUrl = setupUrl(savedInstanceState);

		new MyAsyncTask().execute(myUrl);

	}

	private class MyAsyncTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			try {
				URL url = new URL(params[0]);

				URLConnection connection;
				connection = url.openConnection();

				HttpURLConnection httpConnection = (HttpURLConnection) connection;
				int responseCode = httpConnection.getResponseCode();

				if (responseCode == HttpURLConnection.HTTP_OK) {
					InputStream in = httpConnection.getInputStream();

					DocumentBuilderFactory dbf = DocumentBuilderFactory
							.newInstance();
					DocumentBuilder db = dbf.newDocumentBuilder();

					// Parse the Trip feed.
					Document dom = db.parse(in);
					Element docEle = dom.getDocumentElement();

					// Get a list of each Trip entry.
					NodeList nl = docEle.getElementsByTagName("Trip");
					if (nl != null && nl.getLength() > 0) {
						for (int i = 0; i < nl.getLength(); i++) {
							Trip trip = new Trip();

							NodeList nl2 = docEle.getElementsByTagName("Leg");
							for (int j = 0; j < nl2.getLength(); j++) {
								Element legElem = (Element) nl2.item(j);
								Element originElem = (Element) legElem
										.getElementsByTagName("Origin").item(0);
								Element destElem = (Element) legElem
										.getElementsByTagName("Destination")
										.item(0);
								Element notesElem = (Element) legElem
										.getElementsByTagName("Notes").item(0);
								Element journeyDetElem = (Element) legElem
										.getElementsByTagName(
												"JourneyDetailRef").item(0);

								String legName = legElem.getAttribute("name");
								String legType = legElem.getAttribute("type");

								String originName = originElem
										.getAttribute("name");
								String originType = originElem
										.getAttribute("type");
								String originTime = originElem
										.getAttribute("time");
								String originDate = originElem
										.getAttribute("date");

								String destinationName = destElem
										.getAttribute("name");
								String destinationType = destElem
										.getAttribute("type");
								String destinationTime = destElem
										.getAttribute("time");
								String destinationDate = destElem
										.getAttribute("date");

								String notesText = notesElem
										.getAttribute("text");

								Leg newLeg = new Leg();

								if (journeyDetElem != null) {
									String journeyDetailRef = journeyDetElem
											.getAttribute("ref");
									newLeg.setJourneyDetailRef(journeyDetailRef);
								}
								
								newLeg.setId(j+1);
								newLeg.setLegName(legName);
								newLeg.setLegType(legType);

								newLeg.setOriginName(originName);
								newLeg.setOriginType(originType);
								newLeg.setOriginTime(originTime);
								newLeg.setOriginDate(originDate);

								newLeg.setDestinationName(destinationName);
								newLeg.setDestinationType(destinationType);
								newLeg.setDestinationTime(destinationTime);
								newLeg.setDestinationDate(destinationDate);
								newLeg.setNotesText(notesText);
								
								trip.addLeg(newLeg);
							}
							tripList.add(trip);
							
						}
					}
				}
			} catch (MalformedURLException e) {
				Log.d(TAG, "MalformedURLException");
			} catch (IOException e) {
				Log.d(TAG, "IOException");
			} catch (ParserConfigurationException e) {
				Log.d(TAG, "Parser Configuration Exception");
			} catch (SAXException e) {
				Log.d(TAG, "SAX Exception");
			}
			return null;
		}

		protected void onPostExecute(String result) {
			
			String firstTripStartTime = tripList.get(0).getLegs().get(0).getOriginTime();
			String firstTripArrivalTime = tripList.get(0).getLegs().get(2).getDestinationTime();
			String firstTripTransport = tripList.get(0).getLegs().get(1).getLegType();
			
			String secondTripStartTime = tripList.get(1).getLegs().get(3).getOriginTime();
			String secondTripArrivalTime = tripList.get(1).getLegs().get(5).getDestinationTime();
			String secondTripTransport = tripList.get(1).getLegs().get(4).getLegType();
			
			String thirdTripStartTime = tripList.get(2).getLegs().get(6).getOriginTime();
			String thirdTripArrivalTime = tripList.get(2).getLegs().get(8).getDestinationTime();
			String thirdTripTransport = tripList.get(2).getLegs().get(7).getLegType();
			
			buttonFirstTrip.setText("Afg:" + firstTripStartTime + " | Ank:" + firstTripArrivalTime + " | " + firstTripTransport);
			buttonSecondTrip.setText("Afg:" + secondTripStartTime + " | Ank:" + secondTripArrivalTime + " | " + secondTripTransport);
			buttonThirdTrip.setText("Afg:" + thirdTripStartTime + " | Ank:" + thirdTripArrivalTime + " | " + thirdTripTransport);
		}

	}

	private String setupUrl(Bundle savedInstanceState) {
		String myUrl;
		String tempUrl = baseUrl + getString(R.string.trip_feed);

		// Get data fra originLocation
		if (savedInstanceState.getString("originCoordName") != null) {
			originName = savedInstanceState.getString("originCoordName");
		}
		if (savedInstanceState.getString("originLocationType") != null) {
			originType = savedInstanceState.getString("originLocationType");

		}
		if (savedInstanceState.getString("originCoordX") != null) {
			originX = savedInstanceState.getString("originCoordX");

		}
		if (savedInstanceState.getString("originCoordY") != null) {
			originY = savedInstanceState.getString("originCoordY");

		}
		if (savedInstanceState.getString("originId") != null) {
			originId = savedInstanceState.getString("originId");

		}

		// Get data fra destLocation
		if (savedInstanceState.getString("destCoordName") != null) {
			destName = savedInstanceState.getString("destCoordName");

		}
		if (savedInstanceState.getString("destLocationType") != null) {
			destType = savedInstanceState.getString("destLocationType");
		}
		if (savedInstanceState.getString("destCoordX") != null) {
			destX = savedInstanceState.getString("destCoordX");
		}
		if (savedInstanceState.getString("destCoordY") != null) {
			destY = savedInstanceState.getString("destCoordY");
		}
		if (savedInstanceState.getString("destCoordId") != null) {
			destId = savedInstanceState.getString("destCoordId");
		}

		// Get date and time
		if (savedInstanceState.getString("time") != null) {
			time = savedInstanceState.getString("time");
		}
		if (savedInstanceState.getString("date") != null) {
			date = savedInstanceState.getString("date");
		}
		tvDate.setText(date);

		// Get data from chosed transport method
		if (savedInstanceState.getString("useBus") != null) {
			useBus = savedInstanceState.getString("useBus");
		}
		if (savedInstanceState.getString("useTog") != null) {
			useTrain = savedInstanceState.getString("useTog");
		}
		if (savedInstanceState.getString("useMetro") != null) {
			useMetro = savedInstanceState.getString("useMetro");
		}

		if (originId != null) {
			if (destId != null) {
				// http://<baseurl>/trip?originId=8600626&destId=<xInteger>&useBus=0
				tempUrl = tempUrl + "originId=" + originId + "&destId="
						+ destId + "&date=" + date + "&time="
						+ time + "&useBus=" + useBus + "&useTog="
						+ useTrain + "&useMetro=" + useMetro;
			} else {
				// http://<baseurl>/trip?originId=8600626&destCoordX=<xInteger>&destCoordY=<yInteger>&destCoordName=<NameOfDestination>&useBus=0
				tempUrl = tempUrl + "originId=" + originId + "&destCoordX="
						+ destX + "&destCoordY=" + destY
						+ "&destCoordName=" + destName + "&date="
						+ date + "&time=" + time + "&useBus="
						+ useBus + "&useTog=" + useTrain + "&useMetro="
						+ useMetro;
			}
		} else {
			if (destId != null) {
				// http://<baseurl>/trip?originCoordX=<Integer>&originCoordY=<Integer>&originCoordName=<NameOfOrigin>&destId=<Integer>
				tempUrl = tempUrl + "originCoordX=" + originX
						+ "&originCoordY=" + originY + "&originCoordName="
						+ originName + "&destId=" + destId + "&date="
						+ date + "&time=" + time + "&useBus="
						+ useBus + "&useTog=" + useTrain + "&useMetro="
						+ useMetro;
			} else {
				// http://<baseurl>/trip?originCoordX=<Integer>&originCoordY=<Integer>&originCoordName=<NameOfOrigin>&destCoordX=<xInteger>&destCoordY=<yInteger>&destCoordName=<NameOfDestination>&useBus=0
				tempUrl = tempUrl + "originCoordX=" + originX
						+ "&originCoordY=" + originY + "&originCoordName="
						+ originName + "&destCoordX=" + destX
						+ "&destCoordY=" + destY + "&destCoordName="
						+ destName + "&date=" + date + "&time="
						+ time + "&useBus=" + useBus + "&useTog="
						+ useTrain + "&useMetro=" + useMetro;
			}
		}
		tempUrl = tempUrl.replaceAll(" ", "%20");
		myUrl = tempUrl;
		return myUrl;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.page2, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */

	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	public void firstTrip(View v) {
		Intent intent = new Intent(Page2.this, Page3.class);
		startActivity(intent);
	}

	public void secondTrip(View v) {
		Intent intent = new Intent(Page2.this, Page3.class);
		startActivity(intent);
	}

	public void thirdTrip(View v) {
		Intent intent = new Intent(Page2.this, Page3.class);
		startActivity(intent);
	}

}
